<script>
import UserApi from '../../api/user'
import UserForm from '../../components/user/UserForm.vue'

export default {
  components: {
    UserForm,
  },
  inject: ['reload'],
  data() {
    return {
      userList: [],
      total: 0,
      pageSize: 7,
      curPage: 0,
      limit: -1,
      offset: -1,
      modalShow: false, //是否显示
      modalTitle: '', //模态框标题
      modalAction: 0, //模态框索引
      newUser: {
        username: '',
        nickname: '',
        truename: '',
        avatar: '',
        role: '',
      },
      editUser: {
        id: 0,
        username: '',
        nickname: '',
        truename: '',
        avatar: '',
        role: '',
      },
      deleteUserId: 0,
      resetPasswordUserId: 0,
    }
  },
  methods: {
    async getUserList(limit = -1, offset = -1) {
      try {
        const api = new UserApi()
        let res = await api.findAll(limit, offset)
        this.userList = res.data
        console.log(this.userList)
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    async getCount() {
      try {
        const api = new UserApi()
        let res = await api.getCount()
        console.log(res.data.result.total)
        this.total = res.data.result.total
        console.log(this.total)
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    goto(page) {
      this.curPage = page
      this.offset = (page - 1) * this.pageSize
      this.getUserList(this.limit, this.offset)
    },
    closeModal() {
      this.modalShow = false
      this.modalTitle = ''
      this.modalAction = 0
    },
    showAddModal() {
      this.modalShow = true
      this.modalTitle = '新增用户'
      this.modalAction = 1
    },
    async add() {
      try {
        const api = new UserApi()
        let res = await api.add(this.newUser)
        if (res.code === 201 && res.data.lastID > 0) {
          this.$myMessageBox(res.msg)
          this.closeModal()
          // 直接调用已存在的数据获取方法
          //   await this.getUserList(this.limit, this.offset) // 刷新当前页数据
          //   await this.getCount() // 更新总数（可选，如果分页需要）
          this.reload() //刷新页面
        }
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    showEditModal(user) {
      this.modalShow = true
      this.modalTitle = '新增用户'
      this.modalAction = 2
      this.editUser = {}
      this.editUser = user
    },
    async edit() {
      try {
        const api = new UserApi()
        let res = await api.edit(this.editUser)
        if (res.code === 200 && res.data.changes > 0) {
          this.$myMessageBox(res.msg)
          this.closeModal()
          this.reload() //刷新
        }
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    showDeleteModal(userId) {
      this.modalShow = true
      this.modalTitle = '删除用户'
      this.modalAction = 3
      this.deleteUserId = userId
    },
    async del() {
      try {
        const api = new UserApi()
        let res = await api.delete(this.deleteUserId)
        if (res.code === 204 && res.data.changes > 0) {
          this.$myMessageBox(res.msg)
          this.closeModal()
          this.reload() //刷新
        }
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    showResetPasswordModal(userId) {
      this.modalShow = true
      this.modalTitle = '重置用户密码'
      this.modalAction = 4
      this.resetPasswordUserId = userId
    },
    async resetPassword() {
      try {
        const api = new UserApi()
        let res = await api.resetPassword(this.resetPasswordUserId)
        if (res.code === 200 && res.data.changes > 0) {
          this.$myMessageBox(res.msg)
          this.closeModal()
          this.reload() //刷新
        }
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
  },
  async mounted() {
    this.curPage = 1
    this.limit = this.pageSize
    this.offset = 0
    await this.getCount()
    await this.getUserList(this.limit, this.offset)
  },
  computed: {
    roleName() {
      return (role) => {
        return role === 1 ? '管理员' : '普通用户'
      }
    },
    formatLastLoginTime() {
      return (time) => {
        return new Date(time).toLocaleString()
      }
    },
  },
}
</script>

<template>
  <div class="admin-user-list">
    <table>
      <caption>
        <a class="button" href="javascript:void(0);" @click="showAddModal">新增</a>
      </caption>
      <thead>
        <tr>
          <th>&nbsp;</th>
          <th>序号</th>
          <th>用户名</th>
          <th>头像</th>
          <th>昵称</th>
          <th>姓名</th>
          <th>角色</th>
          <th>最后登录时间</th>
          <th>最后登录IP</th>
          <th>登录次数</th>
          <th>&nbsp;</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(user, index) in userList" :key="user.id">
          <td><input type="checkbox" :value="user.id" /></td>
          <td>{{ index + 1 }}</td>
          <td>{{ user.username }}</td>
          <td>{{ user.avatar }}</td>
          <td>{{ user.nickname }}</td>
          <td>{{ user.truename }}</td>
          <td>{{ roleName(user.role) }}</td>
          <td>{{ formatLastLoginTime(user.lastLoginTime) }}</td>
          <td>{{ user.lastLoginIp }}</td>
          <td>{{ user.loginCount }}</td>
          <td>
            <a class="button" href="javascript:void(0);" @click="showEditModal(user)">编辑</a>
            <a class="button" href="javascript:void(0);" @click="showDeleteModal(user.id)">删除</a>
            <a class="button" href="javascript:void(0);" @click="showResetPasswordModal(user.id)">重置密码</a>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="11">
            <my-pagination
              :total="total"
              :page-size="pageSize"
              :cur-page="curPage"
              :show-info="true"
              @goto="goto"
            />
          </td>
        </tr>
      </tfoot>
    </table>
    <my-modal :title="modalTitle" @close-modal="closeModal" v-if="modalShow">
      <template v-if="modalAction === 1">
        <user-form v-model="newUser" :is-add="true" @user-save="add" />
      </template>
      <template v-if="modalAction === 2">
        <user-form v-model="editUser" :is-add="false" @user-save="edit" />
      </template>
      <template v-if="modalAction === 3">
        <div>
          <span>是否删除？</span>
          <button @click="del">确定</button>
          <button @click="closeModal">取消</button>
        </div>
      </template>
      <template v-if="modalAction === 4">
        <div>
          <span>是否重置密码？</span>
          <span>重置默认密码为：123456</span>
          <button @click="resetPassword">确定</button>
          <button @click="closeModal">取消</button>
        </div>
      </template>
    </my-modal>
  </div>
</template>

<style scoped>
table {
  border: solid 1px #e2daff;
  margin: auto;
  border-collapse: collapse;
  width: 100%;
}

caption {
  text-align: right;
  padding: 8px;
}

tr {
  border-top: solid 1px #e2daff;
  border-bottom: solid 1px #e2daff;
}

th,
td {
  padding: 8px;
}
</style>
